package com.ambitor.ipro.demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.IData;
import com.ambitor.ipro.entities.Result;
import com.ambitor.ipro.exceptions.ProException;
import com.ambitor.ipro.service.TopClient;
import com.ambitor.ipro.service.TopService;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.SkyenccUtil;
import com.ambitor.ipro.util.TaobaoUtil;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.FileItem;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.ItemSearch;
import com.taobao.api.domain.SellerCat;
import com.taobao.api.domain.User;
import com.taobao.api.domain.UserSubscribe;
import com.taobao.api.request.AppstoreSubscribeGetRequest;
import com.taobao.api.request.ItemGetRequest;
import com.taobao.api.request.ItemsInventoryGetRequest;
import com.taobao.api.request.ItemsOnsaleGetRequest;
import com.taobao.api.request.ItemsSearchRequest;
import com.taobao.api.request.PictureUploadRequest;
import com.taobao.api.request.UserGetRequest;
import com.taobao.api.response.AppstoreSubscribeGetResponse;
import com.taobao.api.response.ItemGetResponse;
import com.taobao.api.response.ItemsInventoryGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
import com.taobao.api.response.ItemsSearchResponse;
import com.taobao.api.response.UserGetResponse;

/**
 * Here is a demostration for class TaobaoCallService and
 * TaobaoBatchCallService.
 * 
 * @author bugxiaoya
 * 
 */
public class TestCallClient {
	protected static final Logger logger = LoggerFactory
			.getLogger(TestCallClient.class);

	public static void main(String args[]) throws Exception {
		testSubscribe3();
	}

	public static String getFavUrl(String shopUrl) throws IOException {
		String addCollectionUrl = "";
		boolean result = true;
		HttpURLConnection urlConn = null;
		InputStream in = null;
		BufferedReader rd = null;
		URL url = new URL(shopUrl);
		urlConn = (HttpURLConnection) url.openConnection();
		urlConn.setRequestMethod("POST");
		urlConn.setDoOutput(true);
		urlConn.getOutputStream().flush();
		urlConn.getOutputStream().close();
		in = urlConn.getInputStream();
		rd = new BufferedReader(new InputStreamReader(in, "GB2312"), 8192);
		String itemId = "";
		String ownerId = "";
		while (rd.read() != -1) {
			String tempStr = rd.readLine();
			if (tempStr.indexOf(" collection xshop_sc") > -1) {
				int start = tempStr.indexOf("itemid=");
				String temp = tempStr.substring(start + 7);
				int end = temp.indexOf("&");
				itemId = temp.substring(0, end);
				start = tempStr.indexOf("ownerid=");
				temp = tempStr.substring(start + 8);
				end = temp.indexOf("\"");
				ownerId = temp.substring(0, end);
				if (!itemId.equals("") && !ownerId.equals("")) {
					break;
				}
			}
		}
		if (itemId.equals("") || ownerId.equals("")) {
			result = false;
		}
		if (result) {
			// String shopIntroduceUrl = shopUrl + "/shop/xshop/shop_intro.htm";
			// String creditUrl = ownerId;
			// int index = ownerId.indexOf("&scjjc=");
			// if (index >= 0) {
			// creditUrl = ownerId.substring(0, index);
			// }
			// String creditEvaluationUrl = " http://rate.taobao.com/user-rate-"
			// + creditUrl + ".htm";
			// String personalSpaceUrl = "
			// http://forum.taobao.com/myspace.htm?ownerid="
			// + ownerId;
			addCollectionUrl = " http://favorite.taobao.com/popup/add_collection.htm?itemid="
					+ itemId + "&amp;itemtype=0&amp;ownerid=" + ownerId;
		}
		if (urlConn != null)
			urlConn.disconnect();
		if (in != null)
			in.close();
		if (rd != null)
			rd.close();
		return addCollectionUrl;
	}

	public static void testCat() {
		TopService topService = new TopService(Constants.EVN_SWITCH,
				"12157195", "b6b6494ceab4b8bc4761b48041cf694b");
		String sessionId = "20460cb1d6df546c457e55d085c3558753af3";
		try {
			List<Item> items = topService.getOnSaleItemsOfSpecificSellerCat(
					sessionId, "cp小屋", "311075977");
			System.out.println();
		} catch (ProException e) {
			e.printStackTrace();
		}
	}

	public static void getUser() {
		String nick = "魅之枫";
		TaobaoClient topClient = new DefaultTaobaoClient(
				Constants.API_SERVICE_URL, "12157195",
				"b6b6494ceab4b8bc4761b48041cf694b");
		UserGetRequest req = new UserGetRequest();
		req
				.setFields("sex,location.city,location.district,location.state,seller_credit,type,"
						+ "location.country,email,alipay_account");
		req.setNick(nick);
		UserGetResponse response = null;
		try {
			response = topClient.execute(req,
					"22725d38984fbf640caec91b609982efdd1a7");
		} catch (ApiException e) {
			e.printStackTrace();
		}
		User user = response.getUser();
		System.out.println("Sex:" + user.getSex());
		System.out.println("Type:" + user.getType());
		System.out.println("birthday:" + user.getBirthday());
		System.out.println("avatar:" + user.getAvatar());
		System.out.println("country:" + user.getLocation().getCountry());
		System.out.println("city:" + user.getLocation().getCity());
		System.out.println("state:" + user.getLocation().getState());
		System.out.println("coutry:" + user.getLocation().getCountry());

		System.out.println("Email:" + user.getEmail());
		System.out.println("AlipayAccount:" + user.getAlipayAccount());
	}

	public static void searchItems() {
		String nick = "bugxiaoya";
		TaobaoClient topClient = new DefaultTaobaoClient(
				Constants.API_SERVICE_URL, "12157195",
				"b6b6494ceab4b8bc4761b48041cf694b");
		ItemsSearchRequest req = new ItemsSearchRequest();
		req.setFields("num_iid,title,volume");
		req.setNicks(nick);
		req.setQ("【新品】");
		ItemsSearchResponse response = null;
		try {
			response = topClient.execute(req);
		} catch (ApiException e) {
			e.printStackTrace();
		}
		ItemSearch itemSearch = response.getItemSearch();
		List<Item> items = itemSearch.getItems();
		for (Item item : items) {
			System.out.println(item.getNumIid() + "," + item.getTitle() + ","
					+ item.getVolume());
		}

	}

	public static void uploadImg() {
		String sessionId = "2948702e99ade6271e12ae73ab0eb7df12a7c";
		TopClient topClient = new TopClient(true, "12157195",
				"b6b6494ceab4b8bc4761b48041cf694b");
		String nick = "bugxiaoya";
		PictureUploadRequest request = new PictureUploadRequest();
		request.setPictureCategoryId(305740903L);
		String path = "introduce.gif";
		FileItem fItem = new FileItem(new File(path));
		request.setImg(fItem);
		request.setImageInputTitle("bugxiaoya.jpg");
		request.setTitle("bugxiaoya");
		try {
			topClient.execute(request, sessionId, nick);
		} catch (ProException e) {
			e.printStackTrace();
		}

	}

	public static void getVersion() throws ProException {
		String p = "aWZyYW1lPTEmdHM9MTI5NzMyNjYyNjc5NiZ2aXNpdG9yX2lkPTQ3MzUwMDg0NSZ2aXNpdG9yX25pY2s95OzI97jnODg1OA==";
		Map<String, String> map = SkyenccUtil.convertBase64StringtoMap(p);
		String nick = map.get("visitor_nick");
		TopService topService = new TopService(Constants.EVN_SWITCH,
				"12157195", "b6b6494ceab4b8bc4761b48041cf694b");
		AppstoreSubscribeGetRequest request = new AppstoreSubscribeGetRequest();
		System.out.println("nick==" + nick);
		request.setNick(nick);
		request.setLeaseId(Constants.LEASE_ID);
		UserSubscribe userSubsc = topService.getSubscribeInfo(nick,
				Constants.LEASE_ID);
		System.out.println("userSubsc==" + userSubsc.getStatus());
		System.out.println("userSubsc==" + userSubsc.getVersionNo());
	}

	public static void getSellerCats() throws ProException {
		TopService topService = new TopService(true, "12157195",
				"b6b6494ceab4b8bc4761b48041cf694b");
		String nick = "bugxiaoya";
		List<SellerCat> cats = topService.getSellerCats(nick);
		for (SellerCat cat : cats) {
			System.out.println(cat.getName());
		}
	}

	public static void testException() {
		try {
			int index = 1 / 0;
			System.out.println(index);
		} catch (java.lang.ArithmeticException e) {
			System.out.println(e.toString());
			StringBuilder stackTraceStr = new StringBuilder();
			StackTraceElement[] elements = e.getStackTrace();
			for (StackTraceElement element : elements) {
				stackTraceStr.append(element.toString());
				stackTraceStr.append("\n");
			}
			System.out.println(stackTraceStr);
		}
	}

	@SuppressWarnings("unused")
	private static void uninstall1() throws Exception {
		String sessionId = "29487dbf1633d3790610cd757e0167d806700";
		TopService topService = new TopService(true, "12185704",
				"1018afeb44de578722258f6c48661acf");
		String nick = "bugxiaoya";
		List<Item> itemList = topService.getAllItems(sessionId, nick);
		int i = 0;
		for (Item item : itemList) {
			try {
				i++;
				logger.info("开始修改第" + i + "个宝贝：" + item.getTitle());
				topService.updateItemDesc(sessionId, nick, item.getNumIid(),
						item.getDesc() + "这是本好书呀！");
				logger.info("第" + i + "个宝贝：" + item.getTitle() + "修改成功");
			} catch (Exception e) {
				logger.info("第" + i + "个宝贝：" + item.getTitle() + "修改失败", e);
			}
		}
	}

	@SuppressWarnings("unused")
	private static void uninstall2() throws Exception {
		String sessionId = "24993b4dee30897fcfc4123ff7211aaf842b8";
		TopService topService = new TopService(true, "12157195",
				"b6b6494ceab4b8bc4761b48041cf694b");
		String nick = "蓝洋之星";
		List<Item> itemList = topService.getAllItems(sessionId, nick);
		int i = 0;
		for (Item item : itemList) {
			try {
				i++;
				logger.info("开始卸载第" + i + "个宝贝：" + item.getTitle());
				topService.uninstallPromotionModule(sessionId, nick, item
						.getNumIid(), "all");
				logger.info("第" + i + "个宝贝：" + item.getTitle() + "卸载成功");
			} catch (Exception e) {
				logger.info("第" + i + "个宝贝：" + item.getTitle() + "卸载失败", e);
			}
		}
	}

	@SuppressWarnings("unused")
	private static void uninstallForOne() throws ProException {
		Long numIid = 5868054015L;
		String sessionId = "29487e5c3f17dbad67305abe4c07f8ffc8b5c";
		TopClient topClient = new TopClient(true, "12157195",
				"b6b6494ceab4b8bc4761b48041cf694b");
		String nick = "bugxiaoya";

		ItemGetRequest request = new ItemGetRequest();
		String fields = "desc";
		request.setFields(fields);
		request.setNumIid(numIid);

		ItemGetResponse rsp = null;
		rsp = topClient.execute(request, sessionId, nick);
		// Result result = TaobaoUtil.parseTaobaoApiResponse(rsp);
	}

	public static void test() throws Exception {
		try {
			logger.info("开始运行");
			@SuppressWarnings("unused")
			int i = 5 / 1;
		} catch (Exception e) {
			throw new Exception("除以0了");
		}
		System.out.println("还能运行嘛");
	}

	public static void getSubs() throws ProException {
		TopService topService = new TopService(true, "12157195",
				"b6b6494ceab4b8bc4761b48041cf694b");
		String[] nicks = { "不miss变坏" };
		for (String nick : nicks) {
			UserSubscribe userSubs = topService.getSubscribeInfo(nick, 0L);
			// System.out.println(nick+"=="+userSubs.getStartDate());
			System.out.println(nick + "==" + userSubs.getVersionNo());
		}
	}

	public static void verify() throws NoSuchAlgorithmException,
			UnsupportedEncodingException {
		String bStr = "b6b6494ceab4b8bc4761b48041cf694bfactMoney0.00gmtCreateDate2010-12-02 13:30:41invalidateDate2011-01-02 00:00:00leaseId22886nick潇洒哥8858oldVersionNo0status2subscType1tadgetCodeservice-0-22886userId473500845validateDate2010-12-02 00:00:00versionNo1b6b6494ceab4b8bc4761b48041cf694b";
		String sign = "F25765E8660533D73B3D61EFAEAADB7E";
		byte[] bytes = MessageDigest.getInstance("MD5").digest(
				bStr.toString().getBytes("UTF-8"));
		String encodedString = new String(bytes).toUpperCase();
		System.out.println("sign==" + sign);
		System.out.println("encodedString==" + encodedString);
	}

	public static void updateItemDesc() throws Exception {
		TopService topService = new TopService(false, "test", "test");
		String sessionId = "2948706d2a2c8b012f5d7da8c85c302f106f3";
		topService.updateItemDesc(sessionId, "xiaoya", 1451814163,
				"nullnullnullnullnull");
	}

	public static void getItemDesc() throws ProException {
		TaobaoClient topClient = new DefaultTaobaoClient(
				Constants.API_SANDBOX_SERVICE_URL, "test", "test");
		String sessionId = "283289eb1cdacd9a4437fc1ed24e936c151d9";
		ItemGetRequest request = new ItemGetRequest();
		String fields = "desc";
		request.setFields(fields);
		request.setNumIid(new Long(1451814163));
		ItemGetResponse rsp = null;
		try {
			rsp = topClient.execute(request, sessionId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Item item = rsp.getItem();

		String desc = item.getDesc();
		System.out.println(desc);
	}

	public static void getItemSellerCids() throws ProException, ApiException {
		TaobaoClient topClient = new DefaultTaobaoClient(
				Constants.API_SERVICE_URL, "12157195",
				"b6b6494ceab4b8bc4761b48041cf694b");
		String sessionId = "9487037cd1c1d1dff8e86b992c5df5a0c6ad";
		ItemGetRequest request = new ItemGetRequest();
		String fields = "title,seller_cids";
		request.setFields(fields);
		// request.setNumIid(new Long(5868176619L));
		request.setNumIid(new Long(5868127845L));
		// ,279121024,279120649,
		ItemGetResponse rsp = null;
		try {
			rsp = topClient.execute(request, sessionId);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("cuowu");
		}

		System.out.println(rsp.getBody());
		System.out.println(rsp.getMsg());
		IData data = new DataMap(rsp.getParams());
		System.out.println(data);

		Item item = rsp.getItem();

		String sellerCids = item.getSellerCids();
		System.out.println(sellerCids);
		System.out.println(item.getTitle());

		ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
		req.setFields(fields);
		req.setSellerCids(sellerCids);
		req.setPageNo(new Long(1));
		req.setPageSize(new Long(10));
		ItemsOnsaleGetResponse response = topClient.execute(req, sessionId);
		List<Item> items = response.getItems();
		System.out.println(items.get(0).getTitle());
		System.out.println(items.get(0).getTitle() + "sellerCids=="
				+ items.get(0).getSellerCids());
		System.out.println(items.get(1).getTitle() + "sellerCids=="
				+ items.get(1).getSellerCids());
	}

	public static void testTopClient() throws ProException {
		TopClient topClient = new TopClient(true, "12157195",
				"b6b6494ceab4b8bc4761b48041cf694b");
		ItemsInventoryGetRequest request = new ItemsInventoryGetRequest();
		String fields = "num_iid,title,seller_cids,pic_url,num,price,delist_time,approve_status";
		request.setFields(fields);
		request.setOrderBy("list_time:desc");
		request.setPageNo(new Long(1));
		request.setPageSize(new Long(10));
		String sessionId = "294871cc8d8f7e3590e1ebfb9344045b1c235";

		ItemsInventoryGetResponse response = null;
		response = topClient.execute(request, sessionId, "xiaoya");
		System.out.println("总行数为" + response.getItems());

		/*
		 * if (result.getCode() > 0 && response.getItems() != null &&
		 * response.getItems().size() > 0) { for (Item item :
		 * response.getItems()) { System.out.println("num_iid==" +
		 * item.getNumIid()); System.out.println("title==" + item.getTitle()); } }
		 */
	}

	public static void testDefaultTopClient() {
		TaobaoClient topClient = new DefaultTaobaoClient(
				"http://gw.api.tbsandbox.com/router/rest", "test", "test");
		ItemsOnsaleGetRequest request = new ItemsOnsaleGetRequest();
		String fields = "num_iid,title,seller_cids,pic_url,num,price,delist_time,approve_status";
		request.setFields(fields);
		request.setOrderBy("list_time:desc");
		request.setPageNo(new Long(1));
		request.setPageSize(new Long(10));
		String sessionId = "28326c2907776dc0139bfb5bd0a9eefaf6948";

		ItemsOnsaleGetResponse response = null;
		try {
			response = topClient.execute(request, sessionId);
		} catch (ApiException e) {
			e.printStackTrace();
		}

		Result result = TaobaoUtil.parseTaobaoApiResponse(response);
		System.out.println(result.toString());
		String total = "null";
		if (response.getTotalResults() != null) {
			total = response.getTotalResults() + "";

		}
		List<Item> items = response.getItems();
		if (items == null) {
			System.out.println("原始方式调用本页行数为null");
		} else if (items.size() <= 0) {
			System.out.println("原始方式调用本页行数为0");
		} else {
			System.out.println("原始方式调用本页行数为" + items.size());
		}
		System.out.println("原始方式调用总行数为" + total);

	}

	public static void testJDK2() {
		TaobaoClient topClient = new DefaultTaobaoClient(
				"http://gw.api.tbsandbox.com/router/rest", "test", "test");

		ItemsOnsaleGetRequest request = new ItemsOnsaleGetRequest();
		String fields = "num_iid,title,seller_cids,pic_url,num,price,delist_time,approve_status";
		request.setFields(fields);
		// request.setOrderBy("list_time:desc");
		String sessionId = "24351cd904c7a8da6667bbd99d94621c50082";

		ItemsOnsaleGetResponse response = null;
		try {
			response = topClient.execute(request, sessionId);
		} catch (ApiException e) {
			e.printStackTrace();
		}

		Result result = TaobaoUtil.parseTaobaoApiResponse(response);
		if (result.getCode() > 0 && response.getItems() != null
				&& response.getItems().size() > 0) {
			for (Item item : response.getItems()) {
				System.out.println("num_iid==" + item.getNumIid());
				System.out.println("title==" + item.getTitle());
			}
		}
	}

	public static void testSubscribe1() throws ProException {
		TaobaoClient topClient = new DefaultTaobaoClient(
				"http://gw.api.taobao.com/router/rest", "12157195",
				"b6b6494ceab4b8bc4761b48041cf694b");
		UserSubscribe userSubs = null;
		AppstoreSubscribeGetRequest request = new AppstoreSubscribeGetRequest();
		String nick = "bugxiaoya";
		request.setNick(nick);
		AppstoreSubscribeGetResponse response = null;
		try {
			response = topClient.execute(request, nick);
		} catch (ApiException e) {
			e.printStackTrace();
		}
		userSubs = response.getUserSubscribe();
		if (userSubs == null) {
			System.out.println("null");
		} else {
			System.out.println(response.getBody());
		}
	}

	public static void testSubscribe2() throws ProException {
		UserSubscribe userSubs = null;
		AppstoreSubscribeGetRequest request = new AppstoreSubscribeGetRequest();
		String nick = "bugxiaoya";
		request.setNick(nick);
		AppstoreSubscribeGetResponse response = null;
		TopClient topClient = new TopClient(true, "12157195",
				"b6b6494ceab4b8bc4761b48041cf694b");
		try {
			response = topClient.execute(request, nick);
		} catch (Exception e) {
			e.printStackTrace();
		}
		userSubs = response.getUserSubscribe();
		if (userSubs == null) {
			System.out.println("null");
		} else {
			System.out.println(response.getBody());
		}
	}
	
	public static void testSubscribe3() throws ProException {
		UserSubscribe userSubs = null;
		AppstoreSubscribeGetRequest request = new AppstoreSubscribeGetRequest();
		String nick = "bugxiaoya";
		request.setNick(nick);
		AppstoreSubscribeGetResponse response = null;
		TopService topService = new TopService(true, "12157195",
				"b6b6494ceab4b8bc4761b48041cf694b");
		try {
			userSubs = topService.getSubscribeInfo(nick,null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (userSubs == null) {
			System.out.println("null");
		} else {
			System.out.println(userSubs.getStatus());
		}
	}

}
